package bb.lanxing.device.thirdpart.gpx

import android.app.Application
import android.content.Context
import android.net.Uri
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import bb.lanxing.App
import bb.lanxing.R
import bb.lanxing.lib.devices.sprint.entity.SettingSupports
import bb.lanxing.model.routebook.RouteBookPreview
import bb.lanxing.mvvm.base.viewmodel.BaseViewModel
import bb.lanxing.mvvm.base.viewmodel.SingleLiveEvent
import bb.lanxing.mvvm.routebook.RouteBookBuildRepository
import bb.lanxing.util.AppFileUtils
import bb.lanxing.util.text.UriParse
import com.tencent.open.SocialConstants
import io.ticofab.androidgpxparser.parser.GPXParser
import io.ticofab.androidgpxparser.parser.domain.Gpx
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.util.UUID

class GPXImportViewModel(application: Application) : BaseViewModel(application) {
    val createFromGPXResultLiveData = SingleLiveEvent<Boolean>()
    val generateResult = SingleLiveEvent<Boolean>()
    private val gpx = MutableLiveData<Gpx>()
    private val routeBookPreviewLiveData = MutableLiveData<RouteBookPreview>()

    private var gpxFile: File? = null

    fun getGpxFile(): File? {
        return gpxFile
    }

    fun setGpxFile(file: File) {
        gpxFile = file
    }

    fun getGpx(): LiveData<Gpx> {
        return gpx
    }

    fun getRouteBookPreviewLiveData(): LiveData<RouteBookPreview> {
        return routeBookPreviewLiveData
    }

    fun generateGpx(context: Context, uri: Uri) {
        execute({
            try {
                val fileName = UriParse.getFileName(context, uri)
                val file = File(AppFileUtils.buildExternalDirectoryPath("temp"), fileName)
//            UriParse.saveFileFromUri(context, uri, file.absolutePath)
                val openInputStream = context.contentResolver.openInputStream(uri)
                val bufferedOutputStream =
                    BufferedOutputStream(FileOutputStream(file.absolutePath, false))
                setGpxFile(file)
                AppFileUtils.copyStream(openInputStream, bufferedOutputStream)
                file.apply {
                    var parse = GPXParser().parse(FileInputStream(file))
                    if (null != parse) {
                        if (!GPXextKt.isValid(parse)) {
                            parse = null
                        }
                        if (null != parse) {
                            gpx.postValue(parse)
                            generateResult.postValue(true)
                        } else {
                            generateResult.postValue(false)
                        }
                    }
                }
            } catch (e: Throwable) {
                e.printStackTrace()
                App.getContext().showMessage(R.string.lushu_not_gpx_file)
            }

        }, {
            generateResult.postValue(false)
        }, {

        }, false)
    }

    fun requestGpxPreviewData() {
        execute({
            try {
                val builder = MultipartBody.Builder().setType(MultipartBody.FORM)
                val uuid = UUID.randomUUID().toString()
                val repository = RouteBookBuildRepository.getInstance()
                val build = builder.addFormDataPart("uuid", uuid).addFormDataPart(
                    "upload_file_name",
                    gpxFile!!.name,
                    RequestBody.create(MediaType.parse("application/xml"), gpxFile)
                ).build()
                val result = repository.requestRouteBookPreview(build)
                result?.let {
                    routeBookPreviewLiveData.postValue(it)
                }
            } catch (e: Throwable) {
                e.printStackTrace()
            }
        }, {
            it.printStackTrace()
        }, {

        }, true)
    }

    fun saveGpx(title: String, desc: String, i: Int, d: Double) {
        execute({
            try {
                val builder = MultipartBody.Builder().setType(MultipartBody.FORM)
                val uuid = UUID.randomUUID().toString()
                val repository = RouteBookBuildRepository.getInstance()
                val previewData = routeBookPreviewLiveData.value
                val build = builder.addFormDataPart("uuid", uuid).addFormDataPart("title", title)
                    .addFormDataPart(SettingSupports.SUPPORT_ITEM_SPORT, i.toString())
                    .addFormDataPart(SocialConstants.PARAM_APP_DESC, desc)
                    .addFormDataPart("avgGrade", previewData?.avg_grade.toString() ?: "")
                    .addFormDataPart("distance", previewData?.dis.toString() ?: "")
                    .addFormDataPart("maxAltitude", previewData?.max_altitude.toString() ?: "")
                    .addFormDataPart("minAltitude", previewData?.min_altitude.toString() ?: "")
                    .addFormDataPart("elevationGain", previewData?.elevation_gain.toString() ?: "")
                    .addFormDataPart(
                        "fileId", previewData?.fileId.toString() ?: "0"
                    ).build()
                val result = repository.createFromGPX(build)
                createFromGPXResultLiveData.postValue(result.isSuccess)
            } catch (e: Throwable) {
                e.printStackTrace()
            }
        }, {
            it.printStackTrace()
        }, {

        }, true)
    }
}